package cn.com.thingo.hyintelligent.ui.activity;

import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.google.gson.Gson;
import com.videogo.exception.BaseException;
import com.videogo.openapi.EZHCNetDeviceSDK;
import com.videogo.openapi.EZOpenSDK;
import com.videogo.wificonfig.APWifiConfig;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.com.thingo.hyintelligent.R;
import cn.com.thingo.hyintelligent.app.EzHttpConstants;
import cn.com.thingo.hyintelligent.base.BaseActivity;
import cn.com.thingo.hyintelligent.base.contract.EzWifiApConfigContract;
import cn.com.thingo.hyintelligent.model.bean.BaseBean;
import cn.com.thingo.hyintelligent.model.bean.EzAddDevicePermissionBean;
import cn.com.thingo.hyintelligent.model.bean.EzDeviceStateBean;
import cn.com.thingo.hyintelligent.model.bean.PermissionJsonBean;
import cn.com.thingo.hyintelligent.model.db.UserInfo;
import cn.com.thingo.hyintelligent.presenter.EzWifiApConfigPresenter;
import cn.com.thingo.hyintelligent.util.GsonUtil;
import cn.com.thingo.hyintelligent.util.LogUtil;
import cn.com.thingo.hyintelligent.util.ToastUtil;
import cn.com.thingo.hyintelligent.util.WaitDialogUtils;
import cn.com.thingo.hyintelligent.widget.WaitDialog;

import static cn.com.thingo.hyintelligent.app.EzHttpConstants.ADD_DEVICE_SUCCESS_ACTION;
import static cn.com.thingo.hyintelligent.ui.activity.EzWifiNetConfigActivity.WIFI_PASSWORD;
import static cn.com.thingo.hyintelligent.ui.activity.EzWifiNetConfigActivity.WIFI_SSID;
import static cn.com.thingo.hyintelligent.ui.activity.SearchEzDeviceActivity.BUNDE_SERIANO;
import static cn.com.thingo.hyintelligent.ui.activity.SearchEzDeviceActivity.BUNDE_VERYCODE;

public class EzWifiApConfigActivity extends BaseActivity<EzWifiApConfigPresenter> implements EzWifiApConfigContract.View, View.OnClickListener {
    private String mVerifyCode;
    private String mDeviceSerial;
    private String mSSID;
    private String mPassword;

    private TextView mSSIDTv;
    private TextView mPasswordTv;
    private TextView mTipTv;
    @BindView(R.id.toolbar_left)
    ImageView ivLeft;
    @BindView(R.id.toolbar_title)
    TextView tvTitle;
    @BindView(R.id.reset)
    TextView mResetTv;
    @BindView(R.id.add_device)
    TextView mAddTv;
    @BindView(R.id.ap_progress)
    ProgressBar mProgress;
    private WaitDialog dialog;
    private UserInfo mUserInfo;

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_ezwifi_ap_config;
    }

    @Override
    protected void initEventAndData() throws Exception {
        initData();
        initTitle();
        setListener();
        startAP();
    }

    private void startAP() {
        mProgress.setVisibility(View.VISIBLE);
        mResetTv.setVisibility(View.GONE);
        mAddTv.setVisibility(View.GONE);
        EZOpenSDK.getInstance().startAPConfigWifiWithSsid(mSSID, mPassword, mDeviceSerial, mVerifyCode,
                new APWifiConfig.APConfigCallback() {
                    @Override
                    public void onSuccess() {
                        Log.d("APWifiConfigActivity", "onSuccess");
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mProgress.setVisibility(View.GONE);
                                mResetTv.setVisibility(View.GONE);
                                mAddTv.setVisibility(View.VISIBLE);
                            }
                        });
                    }

                    @Override
                    public void OnError(final int code) {
                        Log.d("APWifiConfigActivity", "OnError");
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mProgress.setVisibility(View.GONE);
                                mResetTv.setVisibility(View.VISIBLE);
                                mAddTv.setVisibility(View.GONE);
                                switch (code) {
                                    case 15:
                                        // TODO: 2018/7/24 超时
                                        break;
                                    case 1:
                                        // TODO: 2018/7/24 参数错误
                                        break;
                                    case 2:
                                        // TODO: 2018/7/24 设备ap热点密码错误
                                        break;
                                    case 3:
                                        // TODO: 2018/7/24  连接ap热点异常
                                        break;
                                    case 4:
                                        // TODO: 2018/7/24 搜索WiFi热点错误
                                        break;
                                    default:
                                        // TODO: 2018/7/24 未知错误
                                        break;
                                }
                            }
                        });
                    }
                });
    }

    private void setListener() {
        mResetTv.setOnClickListener(this);
        mAddTv.setOnClickListener(this);
    }


    private void initTitle() {
        ivLeft.setImageResource(R.mipmap.back);
        tvTitle.setText(R.string.title_activity_connect_device_wifi);
    }

    private void initData() {

        mUserInfo = UserInfo.getInstance();
        Intent intent = getIntent();
        mDeviceSerial = intent.getStringExtra(BUNDE_SERIANO);
        mVerifyCode = intent.getStringExtra(BUNDE_VERYCODE);
        mSSID = getIntent().getStringExtra(WIFI_SSID);
        mPassword = getIntent().getStringExtra(WIFI_PASSWORD);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.reset:
                startAP();
                break;
            case R.id.add_device:
                if (mAddTv.getText().toString().trim().equalsIgnoreCase(getString(R.string.complete_txt))) {
                    // TODO: 2018/6/6 完成
                    Intent intent = new Intent(EzWifiApConfigActivity.this, MainActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                    finish();
                } else {
                    EZOpenSDK.getInstance().setAccessToken(mUserInfo.getAccessToken());
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                EZOpenSDK.getInstance().addDevice(mDeviceSerial, mVerifyCode);
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        PermissionJsonBean bean = new PermissionJsonBean();
                                        bean.setPermission("Get,DevCtrl");
                                        List<String> list = new ArrayList<>();
                                        list.add("dev:" + mDeviceSerial);
                                        bean.setResource(list);
                                        String jsonStr = GsonUtil.GsonString(bean);
                                        mPresenter.addEzDevicePermission(mUserInfo.getAccessToken(), mUserInfo.getUserName(), mUserInfo.getUserName(), jsonStr);

                                        WaitDialogUtils.dismissWaitDialog(dialog);
                                        EZOpenSDK.getInstance().setAccessToken(mUserInfo.getRamAccessToken());
                                    }
                                });
                            } catch (BaseException e) {
                                e.printStackTrace();
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        WaitDialogUtils.dismissWaitDialog(dialog);
                                        mAddTv.setText(R.string.auto_wifi_add_device_failed2);
                                        EZOpenSDK.getInstance().setAccessToken(mUserInfo.getRamAccessToken());
                                    }
                                });
                            }
                        }
                    }).start();
                }
                break;
        }
    }

    @Override
    public void onBackPressedSupport() {
        EZHCNetDeviceSDK.getInstance().stopAPConfigWifiWithSsid();
        super.onBackPressedSupport();
    }


    @Override
    protected void onStop() {
        super.onStop();
    }


    @Override
    public void viewAddEzDevicePermissionResult(BaseBean bean) {
        if (bean.getStatus() == 1) {
            mAddTv.setText(R.string.complete_txt);
            Intent intent = new Intent(ADD_DEVICE_SUCCESS_ACTION);
            sendBroadcast(intent);
        } else {
            mAddTv.setText(R.string.auto_wifi_add_device_failed2);
        }
        ToastUtil.shortShow(bean.getMsg());
    }


    @OnClick({R.id.toolbar_left})
    public void onViewClick(View view) {
        switch (view.getId()) {
            case R.id.toolbar_left:
                finish();
                break;
        }
    }
}
